#!/usr/bin/python
# -*- coding:utf-8 -*-

import requests
#prettytable 并非 python 的内置库，通过 pip install prettytable即可安装
from prettytable import PrettyTable
import os
import threading
import time
import datetime




#开市时间、闭市时间
# 09:15 11:30 13:00 15:00
amStart = 915
amEnd = 1130
pmStart = 1300
pmEnd = 1500
showName = False  #是否显示全称
refreshTime = 3.0  #自动刷新时间

# 获取当前文件（即该Python脚本）所在的目录
current_directory = os.path.dirname(__file__)

f = open(current_directory+"/sina_code.txt",'r')        # txt文件，存储股票代码，一行一个代码，小写字母
codeList = [line.strip() for line in f.readlines()]
f.close()

#获取单个股票信息
def get_sina_full_tick(stk_code):
    '''
    0 000001
    1 长虹华意
    2 5.940  # 今开
    3 5.930  # 昨收
    4 5.890  # 当前价格
    5 5.950  # 最高
    6 5.850  # 最低
    7 5.890  # 买一
    8 5.900  # 卖一
    9 6257950  # 成交量
    10 36913532.000  #  成交额
    11 50  # 买一挂单量
    12 5.890  # 买一价格
    13 68000  # 买二挂单量
    14 5.880  # 买二价格
    15 38900
    16 5.870
    17 60600
    18 5.860
    19 102600
    20 5.850  # 买五价格
    21 29200  # 卖一挂单量
    22 5.900  # 卖一价格
    23 53400
    24 5.910
    25 71200
    26 5.920
    27 43300
    28 5.930
    29 83500
    30 5.940  # 卖五价格
    31 2023-09-21
    32 15:00:00
    33 00";
    '''
    stk_code = str(stk_code)
    #暂时未考虑北交所的标的
    mkt = ''
    if stk_code.isdecimal():
        if ((stk_code[:2] == "60") | (stk_code[:3] == "900") | (stk_code[:3] == "688")):   #上证A股600，上证B股900，科创板688
            mkt = "sh"
        elif ((stk_code[:2] == "43") | (stk_code[:2] == "83") | (stk_code[:2] == "87")): #新三板43和83，87
            mkt = "sb"
        elif ((stk_code[:3] == "000") | (stk_code[:3] == "200")): #深证A股000，深证B股200
            mkt = "sz"
        elif ((stk_code[:3] == "002")): #中小板002
            mkt = "sz"
        elif ((stk_code[:3] == "300")): #创业板300
            mkt = "sz"
        #else:
            #mkt = "sz"        #其他默认sz
   
    url = 'http://hq.sinajs.cn/list=' + mkt + stk_code
    print(url)
    headers = {'referer': 'http://finance.sina.com.cn'}

    stk_text = requests.get(url, headers=headers, timeout=6).text
 
    stk_full_tick = stk_text[13:-3].replace('="',',').split(',')      # 删除、替换无关字符
    return stk_full_tick

#输出表格
def printTable(codeList):
    volumePrice = 0;
    table = PrettyTable(['代码','服务器','云编号/%','IP地址/亿','容量/万手'])
    # 股票代码参考http://www.culmart.com/ds/ds/335.html
    for code2 in ['s_sh000001','s_sz399001','s_sz399006','s_sz399300','s_sz399005']: 
        data2 = get_sina_full_tick(code2)
        #print(data2)
        codeName = data2[1]
        if showName == False:
            codeName = codeName[:-2] + '**'  #屏蔽最后2个字
        codeAmount = round(float(data2[6])/ 10000,2)
        codeVolume = round(float(data2[5])/ 10000,2)

        table.add_row([data2[0],codeName,data2[4],codeAmount,codeVolume])

        if(code2 == 's_sh000001' or code2 == 's_sz399006'):
            volumePrice = str(round(float(volumePrice),2)+round(float(codeAmount),2))
      

    for code in codeList: 
        data = get_sina_full_tick(code)
        codeName = data[1]
        if showName == False:
            codeName = codeName[:-2] + '**'  #屏蔽最后2个字
        codeAmount = round(float(data[10])/ 100000000,2)
        codeVolume = round(float(data[9])/ 1000000,2)

        table.add_row([data[0],codeName,str(round((float(data[4]) - float(data[3])) / float(data[3]) * 100, 2)),codeAmount,codeVolume])
      
        
    print(table)
    print("总成交额："+ volumePrice)


def get():

    os.system("cls")   # 清屏操作
    now = datetime.datetime.now()
    nowTimeInt = int(now.strftime("%H%M"))
    dayOfWeek = now.isoweekday()
    
    print("当前时间：", now)


    if amStart <= nowTimeInt <= amEnd or pmStart <= nowTimeInt <= pmEnd :#开市时间
        if dayOfWeek < 6:   #工作日

            global timer
            timer = threading.Timer(refreshTime, get, [])
            timer.start()
    else:
        time.sleep(5)


    printTable(codeList)


if __name__ == '__main__':

    timer = threading.Timer(refreshTime, get, [])
    timer.start()

    
    #for symbol in codeList:      # 遍历股票列表，逐条输出股票数据
    #    print(get_sina_full_tick(symbol)) 